import React, { Component } from 'react';

export class Login extends Component {
	state = {
		info: {
			username: '',
			password: ''
		}
	}
	handleChangeUsername(e) {
		const { info } = this.state
		this.setState({
			info: {
				...info,
				username: e.target.value
			}
		})
	}
	handleChangePassword(e) {
		const { info } = this.state
		this.setState({
			info: {
				...info,
				password: e.target.value
			}
		})
	}
	handleSubmit(e) {
		e.preventDefault()
		
		const { info } = this.state
		new Promise((resolve, reject) => {
			if(info.username === 'admin' && info.password === '123') {
				setTimeout(resolve, Math.random() * 5000)
			} else {
				setTimeout(reject, Math.random() * 5000)
			}
		}).then(() => {
			const resp = { data: { token: 'XXXXXX', nickname: info.username } }
			const { token, nickname } = resp.data
			localStorage.setItem('token', token);
			localStorage.setItem('nickname', nickname);
			this.props.history.goBack()
		}).catch(() => {
			alert('账户密码必须是admin 和 123')
		})
	}
	render() {
		const { info: { username, password } } = this.state
		return (
			<form onSubmit={e => this.handleSubmit(e)}>
				<input type="text" value={username} onChange={e => this.handleChangeUsername(e)} />
				<input type="text" value={password} onChange={e => this.handleChangePassword(e)} />
				<button type="submit">登录</button>
			</form>
		);
	}
}


